/*
 * @Author: askMeWhy
 * @Date:   2017-12-29 14:44:52
 * @Last Modified by: AskMeWhy
 * @Last Modified time: 2021-02-24 15:42:13
 */
import {
    AJAX_REQUEST,
    AJAX_REQUEST_COMPLETE,
    AJAX_LOADING_TEXT,
    // USER_LOGIN,
    USER_LOGIN_SUCCESS,
    // USER_LOGOUT,
    USER_LOGOUT_SUCCESS,
    // USER_GETINFO,
    USER_GETINFO_SUCCESS,
    USER_REFRESH_TOKEN,
    USER_REFRESH_TOKEN_SUCCESS,
    // DYNAMIC_MENU_ROUTE,
    DYNAMIC_MENU_ROUTE_SUCCESS,
    // AUTH_AREA,
    AUTH_AREA_SUCCESS,
    AUTH_AREA_LOGOUT_SUCCESS,
    AUTH_HISTORY_UPDATE,
    AUTH_HISTORY_REMOVE,
    UPDATE_SELECTED_CONTROL,
    COLLECTLIST
} from "./mutations-types";
import {
    isURL,
    isObject,
    listToTree,
    treeFindPath,
    merge,
    AMapLoad
} from "@/utils";
import { resetRouter } from "@/router";
import { getUserLevel } from "@/inject/core/state";
import Api from "@/services";

export const changeLoadText = {
    changeText({ commit }: any, value: any) {
        commit(AJAX_LOADING_TEXT, value);
    }
};

export const getCollectData = {
    CollectData({ commit }: any, value: any) {
        commit(COLLECTLIST, value);
    }
};

export const otherActions = {
    updateSelectedControl({ commit }: any, value: any) {
        commit(UPDATE_SELECTED_CONTROL, value);
    }
};

export const ajaxActions = {
    ajaxRequestStart({ commit }: any) {
        commit(AJAX_REQUEST);
    },
    ajaxRequestEnd({ commit }: any) {
        setTimeout(() => {
            commit(AJAX_REQUEST_COMPLETE);
        }, 300);
    }
};

// const client = {
//     id: "c2",
//     secret: "secret"
// };
export const userInfoActions = {
    login({ commit, dispatch }: any, payload: any) {
        const { phone, smscode, type, username, password, wxcode, wxstate, jump } = payload;
        // console.log(payload);
        // commit(USER_LOGIN);

        return new Promise(async(resolve, reject) => {
            try {
                // const formData = new FormData();
                // formData.set("username", username);
                // formData.set("password", password);
                // formData.set("client_id", client.id);
                // formData.set("client_secret", client.secret);
                // formData.set("grant_type", "password");

                let postData;
                if (type === '2') {
                    postData = {
                        wxcode,
                        wxstate,
                        type
                    };
                } else if (type === '3') {
                    postData = {
                        username: phone,
                        smscode,
                        type
                    };
                } else if (type === '4') {
                    postData = {
                        wxstate,
                        smscode,
                        type
                    };
                } else {
                    postData = {
                        username,
                        password,
                        type
                    };
                }
                const auth = await Api.server.login({
                    loader: false,
                    // data: formData
                    data: postData
                });
                if (auth.data.code === 2006) {
                    jump();
                    return;
                }

                if (auth.status !== 200 || auth.data.code !== 200) {
                    resolve(auth);
                    return;
                }
                const { data } = auth.data;
                // console.log(data);
                // const testToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsibWFuYWdlbWVudCJdLCJ1c2VyX25hbWUiOiIxODExMzEwODg4OCIsInNjb3BlIjpbIlJPTEVfQURNSU4iLCJST0xFX1VTRVIiLCJST0xFX0FQSSJdLCJleHAiOjE2MDk3Mzc2MzIsInVzZXIiOnsiaWQiOjEzNDU5MjY4OTEwNTEyODY1MjgsImRlcGFydG1lbnRJZCI6MTM0NTkyNTI2MDM4MTM4ODgwMCwidXNlcm5hbWUiOiIxODExMzEwODg4OCIsIm5hbWUiOiLpmYjpvpkiLCJ0ZWwiOiIxODExMzEwODg4OCIsInBvc2l0aW9uIjoi6ZmI6b6ZIiwidG9rZW4iOm51bGx9LCJqdGkiOiI3M2EwMWRlNS1mZmQzLTRmNzktOWMzMi04MDUzZTllYzk4MDQiLCJjbGllbnRfaWQiOiJjMSJ9.NmDJnom6CXuNRQZRRaDUsjReS11n9xvcCcNQmoeHgKk";
                commit(USER_LOGIN_SUCCESS, {
                    token: data.token || "",
                    refreshToken: data.refreshToken || ""
                });
                const info = await dispatch("getInfo", data || {});
                if (info.data.code !== 200) {
                    resolve(info);
                    return;
                }
                const _user: any = info.data.user;
                const _level: any = getUserLevel(_user.orgCategoryId);
                await dispatch("updateAuthArea", {
                    id: ["ADMIN", "OPERATION_ADMIN", "OPERATION"].includes(
                        _level.name
                    )
                        ? 0
                        : (_user.governmentIds && _user.governmentIds[0]) || "",
                    default: true
                });
                resolve(auth);
            } catch (e) {
                reject(e);
            }
        });
    },
    getInfo({ commit }: any, payload: any) {
        // commit(USER_GETINFO);
        return new Promise(async(resolve, reject) => {
            try {
                const response = {
                    data: {
                        user: payload,
                        code: 200
                    }
                };
                // const response = await Api.server.userInfo({
                //     loader: false
                // });
                // console.log(response);
                // if (response.data.code !== 0) {
                //     resolve(response);
                //     return;
                // }
                commit(USER_GETINFO_SUCCESS, response.data.user);
                resolve(response);
            } catch (e) {
                console.log(e);
                commit(USER_LOGOUT_SUCCESS);
                reject(new Error("获取账户信息失败！"));
            }
        });
    },
    refreshToken({ state, commit }: any) {
        commit(USER_REFRESH_TOKEN);
        return new Promise(async(resolve, reject) => {
            try {
                const { data: auth } = await Api.server.refreshToken({
                    data: {
                        refreshToken: state.user.auth.refreshToken || ""
                    }
                });
                commit(USER_REFRESH_TOKEN_SUCCESS, auth.data);
                resolve(auth.data);
            } catch (e) {
                reject(e);
            }
        });
    },
    logout({ commit, dispatch }: any) {
        // commit(USER_LOGOUT);
        return new Promise(resolve => {
            resetRouter();
            commit(USER_LOGOUT_SUCCESS);
            commit(AUTH_AREA_LOGOUT_SUCCESS);
            dispatch("clearAuthHistory");
            resolve(true);
        });
    }
};
const formatRoleList = (list: any[]) => {
    const res: any = {};
    if (list.length === 0) {
        return true;
    }
    for (let index = 0; index < list.length; index++) {
        const _cur = list[index];
        const cur = {
            display: true,
            id: (_cur.id || "") + "",
            url: (_cur.code || "") + "",
            name: (_cur.name || "") + "",
            icon: (_cur.icon || "") + "",
            type: (_cur.type || "") + ""
        };
        const _key = cur.url.split(":")[1];
        res[_key] = true;
    }
    return res;
};
let authList: any = {};
const formatDynamicMenuRouter = (list: any) => {
    const res: any = {
        base: [],
        auth: []
    };
    const menuList: any = [];
    if (list.length === 0) {
        return {
            router: res,
            menuList
        };
    }
    list.forEach((item: any) => {
        const _cur = item;
        const cur = {
            display: true,
            id: (_cur.id || "") + "",
            url: (_cur.code || "") + "",
            name: (_cur.name || "") + "",
            icon: (_cur.icon || "") + "",
            type: (_cur.type || "") + "",
            children: item.children || []
        };
        if (!cur.display) {
            return;
        }
        const _menu: any = {
            _key: cur.id + "",
            path: cur.url,
            meta: {
                title: cur.name,
                icon: cur.icon,
                type: "route",
                requiresAuth: true,
                isTab: true,
                isMenu: true
            }
        };
        // type === 2 代表是权限
        if (cur.children && cur.children.length > 0 && cur.type !== "1") {
            const _route = formatDynamicMenuRouter(cur.children);
            _menu.children = _route.menuList;
            res.base = res.base.concat(_route.router.base);
            res.auth = res.auth.concat(_route.router.auth);
        } else {
            // type === 1 代表是菜单
            if (cur.type === "1") {
                const _keys = cur.url.split(/[/-]/);
                let _key = "";
                for (let i = 0; i < _keys.length; i++) {
                    const _k = _keys[i];
                    _key += _k.substring(0, 1).toUpperCase() + _k.substring(1);
                }
                if (_key) {
                    authList[_key] = formatRoleList(cur.children || []);
                }
            }
            if (cur.url) {
                const _cur: any = {
                    path: "",
                    component: null,
                    meta: {
                        title: cur.name,
                        icon: cur.icon,
                        requiresAuth: true,
                        isTab: true,
                        isMenu: true
                    }
                };
                let _path = "";
                let _name = "";
                // let _url = "";
                if (isURL(cur.url)) {
                    _name = "iframe-" + cur.id;
                    _path = "/" + _name;
                    // _url = "iframe";
                    _cur.meta.url = cur.url;
                } else {
                    _name = cur.url;
                    _path = _name;
                    // _url = cur.url;
                }
                _cur.path = _menu.path = _path;
                _menu._key = _path + cur.id;
                _cur.name = _menu.name = _name;
                // TODO remove full-map/home
                if (cur.url === "full-map/home") {
                    // _cur.meta.requiresAuth = false;
                    res.auth.push(_cur);
                } else {
                    res.base.push(_cur);
                }
                // try {
                //     _cur.component = _import(_url);
                //     // console.log(_cur.component);
                // } catch (error) {
                //     if (error.cancel) {
                //         return;
                //     }
                //     // console.log("formatDynamicMenuRouter==>", cur.url, error);
                // }
            }
        }
        menuList.push(_menu);
    });
    return {
        router: res,
        menuList,
        authList: {
            ...authList
        }
    };
};

export const dynamicRouterListActions = {
    dynamicMenuRouter({ state, commit }: any, isInit?: any) {
        // commit(DYNAMIC_MENU_ROUTE);
        return new Promise(async(resolve, reject) => {
            try {
                const user: any = state.user;
                // const userInfo: any = state.user.userInfo;
                authList = {};
                const response: any = await Api.server["menu/list"]();
                if (response.data.code !== 200) {
                    reject(response);
                    return;
                }
                if (!response.data.data.length) {
                    reject("对不起，你没有权限，请联系管理员。");
                    return;
                }
                const _dynamicRoute = formatDynamicMenuRouter(
                    response.data.data || []
                );
                // console.log(_dynamicRoute);
                // const _dynamicMenuRouters = [
                //     {
                //         path: "",
                //         component: BaseLayout, // 通过这个入口区分哪些页面不需要顶部bar和左侧导航栏
                //         children: _dynamicRoute.router
                //     },
                //     {
                //         path: "*",
                //         redirect: "/404"
                //     }
                // ];
                // router.addRoutes(_dynamicMenuRouters);
                if (!isInit) {
                    commit(DYNAMIC_MENU_ROUTE_SUCCESS, _dynamicRoute.menuList);
                }
                commit(USER_LOGIN_SUCCESS, {
                    ...user.auth,
                    list: _dynamicRoute.authList
                });
                commit("setMenuList", _dynamicRoute.menuList);
                // console.log("_dynamicRoute", _dynamicRoute);

                resolve({
                    data: {
                        code: 200,
                        data: _dynamicRoute
                    }
                });
            } catch (e) {
                reject(e);
            }
        });
    }
};

class AuthLinkInfo {
    async getAuthLink(ids: any[]) {
        if (ids.length === 0) {
            return [];
        }
        if (ids[0] === 0) {
            return ["运营专区"];
        }
        const response = await this.getSelectList(ids);
        // const response = [{
        //     province: {
        //         id: "1",
        //         name: "北京市",
        //         code: 110000
        //     },
        //     city: {
        //         id: "2",
        //         name: "北京市2",
        //         code: 2224
        //     },
        //     area: {
        //         id: "4",
        //         name: "北京市4",
        //         code: 22264
        //     },
        //     town: {
        //         id: "5",
        //         name: "北京市5",
        //         code: 22265
        //     },
        //     village: {
        //         id: "6",
        //         name: "北京市6",
        //         code: 22266
        //     }
        // }];
        let option: any = [];
        for (let j = 0; j < response.length; j++) {
            const curRes = response[j];
            if (isObject(curRes)) {
                const list: any[] = [
                    "province",
                    "city",
                    "area",
                    "town",
                    "village"
                ];
                const _option: any = [];
                for (let i = 0; i < list.length; i++) {
                    const cur = list[i];
                    const _rCur = curRes[cur];
                    if (_rCur && _rCur.id) {
                        _option[i] = {
                            parentId: i === 0 ? null : _option[i - 1].value,
                            label: _rCur.name,
                            id: _rCur.id || "",
                            value: _rCur.code + "",
                            leaf: i === list.length - 1
                        };
                    } else {
                        break;
                    }
                }
                option = option.concat(
                    _option.filter((cur: any) => {
                        const _oI: any = option.findIndex(
                            (oCur: any) => cur.value === oCur.value
                        );
                        if (_oI === -1) {
                            return true;
                        } else {
                            option[_oI] = cur;
                            return false;
                        }
                        // return option.findIndex((oCur: any) => cur.value === oCur.value) === -1;
                    })
                );
            }
        }
        return treeFindPath(
            listToTree(option),
            (node: any) => {
                return node.id === ids[0];
            },
            { value: "label" }
        );
    }

    async getSelectList(ids: any[]) {
        const url = "cityAuthLink";
        // let data: any[] = [];
        // data = (ids || []).map((cur: any) => {
        //     return Number(cur);
        // });
        let data: any = {};
        data = {
            governmentIds: ids || []
        };
        const response = await Api.server[url]({
            loader: false,
            data
        });
        if (
            (!response.data && !response.response) ||
            (response.response && response.response.status !== 200) ||
            response.data.code !== 200
        ) {
            return [];
        }
        return response.data.data;
    }
}

const authLinkInfo = new AuthLinkInfo();
export const authAreaActions = {
    updateAuthArea({ state, commit, dispatch }: any, payload: any) {
        return new Promise(async(resolve, reject) => {
            if (payload.replace) {
                resolve(true);
                return;
            }
            let response: any = {};
            const user: any = state.user.userInfo;
            const authHistory: any = merge(true, {}, state.authHistory || {});
            let authHistoryList: any[] = authHistory.list || [];
            const _length = authHistoryList.length;
            const _backStep = payload.backStep || 1;
            if (payload.back) {
                const lastItem: any =
                    _length - _backStep <= 1
                        ? authHistoryList[0]
                        : authHistoryList[_length - _backStep - 1];
                payload.id = lastItem.id;
            }
            if (payload.id.toString() === "0" || payload.default) {
                response = {
                    data: {
                        data: {
                            ...user,
                            governmentId: user.governmentIds[0] || ""
                        }
                    }
                };
            } else {
                response = await Api.server["user/getAreaInfo"]({
                    data: {
                        id: payload.id
                    }
                });
                if (
                    (!response.data && !response.response) ||
                    (response.response && response.response.status !== 200) ||
                    response.data.code !== 200
                ) {
                    reject(response);
                    return;
                }
            }
            const data: any = response.data.data || {};
            const _level: any = getUserLevel(data.orgCategoryId || "");
            commit(AUTH_AREA_SUCCESS, {
                governmentId:
                    payload.id.toString() === "0" &&
                    ["ADMIN", "OPERATION_ADMIN", "OPERATION"].includes(
                        _level.name
                    )
                        ? 0
                        : data.governmentId || "",
                departmentId: user.departmentId || "",
                orgCategoryId: data.orgCategoryId || "",
                cityCode: data.cityCode || "",
                orgCategorySourceId: user.realOrgCategoryId || "",
                optionId: payload.id,
                level: _level
            });
            const _index = authHistoryList.findIndex(
                (cur: any) => cur.id === payload.id
            );
            let _item: any = {};
            if (_index !== -1) {
                _item = authHistoryList[_index];
            } else {
                const labels: any = await authLinkInfo.getAuthLink([
                    payload.id
                ]);
                _item = {
                    id: payload.id + "",
                    label: labels.join("/"),
                    areaName: labels[labels.length - 1]
                };
            }
            if (!payload.replace) {
                if (payload.back) {
                    authHistoryList =
                        _length - _backStep <= 1
                            ? authHistoryList.slice(0, 1)
                            : authHistoryList.slice(0, _length - _backStep);
                } else {
                    authHistoryList.push(_item);
                }
            }
            dispatch("updateAuthHistory", {
                list: authHistoryList
            });
            if (!payload.replace && !payload.default) {
                // dispatch("defaultPage").then((_u: any) => {
                //     console.log(_u);
                //     window.location.href = "/#" + _u;
                // });
                window.location.href = "/";
            }
            resolve(true);
        });
    }
};

export const authHistoryActions = {
    updateAuthHistory({ commit }: any, payload: any) {
        commit(AUTH_HISTORY_UPDATE, payload);
    },
    clearAuthHistory({ commit }: any) {
        commit(AUTH_HISTORY_REMOVE);
    }
};

export const aMapActions = {
    loadAMap({ commit }: any) {
        return new Promise(async(resolve, reject) => {
            try {
                // 正式用的key
                const _aMap = await AMapLoad(
                    "1c55ba0738bea444eeaba501290d1428"
                );

                commit("initAMap", _aMap);
                resolve(_aMap);
            } catch (e) {
                reject(e);
            }
        });
    }
};

export const importAction = {
    importNotice({ commit }: any, payload: any) {
        if (!commit) console.log("");
        return new Promise(async(resolve, reject) => {
            const res = await Api.server["moduleManage/collection/getNotice"]({
                data: {
                    formId: payload.formId
                }
            });
            if (res.data.code === 200) {
                resolve(res.data.data);
            } else {
                reject(res.data.message);
            }
        });
    }
};

export const menuListActions = {
    saveMenuList({ commit }: any, payload: any) {
        commit("setMenuList", payload);
    },
    defaultPage({ state }: any) {
        return new Promise(async resolve => {
            const { authArea, menuList, authHistory } = state;
            let authId = "";
            // 有过权限切换的，属于管理员
            if (authHistory.list.length > 1) {
                authId = (Number(authArea.orgCategoryId) - 1).toString();
            } else {
                authId = authArea.orgCategorySourceId.toString();
            }
            const authName = getUserLevel(authId).name;
            const allMenuPath: any[] = [];
            menuList.forEach((item: any) => {
                const path = item._path || "";
                if (item.children && item.children.length) {
                    item.children.forEach((it: any) => {
                        allMenuPath.push(path + (it._path || ""));
                    });
                } else {
                    allMenuPath.push(path);
                }
            });
            let url = "";
            switch (authName) {
            case "ADMIN":
                break;
            case "OPERATION_ADMIN":
                break;
            case "OPERATION":
                url = "/resource-manage/user-add";
                break;
            case "REGIONAL_ADMIN":
                url = "/system-manage/town";
                break;
            case "REGIONAL":
                url = "/system-manage/town";
                break;
            case "TOWN_ADMIN":
                url = "/system-manage/role-manage";
                break;
            case "TOWN":
                url = "/";
                break;
            case "VILLAGE_ADMIN":
                break;
            case "VILLAGE":
                url = "/overview";
                break;
            default:
                break;
            }
            if (!url || !allMenuPath.includes(url)) {
                url = allMenuPath[0] || "/";
            }
            resolve(url);
        });
    }
};
